package com.clothing.controller.app;

import java.util.Iterator;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.clothing.CommonAttributes;
import com.clothing.bean.ArticleJson;
import com.clothing.controller.BaseController;
import com.clothing.entity.Article;
import com.clothing.entity.Article.Status;
import com.clothing.entity.ArticleImage;
import com.clothing.entity.ArticlePraise;
import com.clothing.entity.ArticleType;
import com.clothing.entity.User;
import com.clothing.service.ArticlePraiseService;
import com.clothing.service.ArticleService;
import com.clothing.service.ArticleTypeService;
import com.clothing.service.UserService;
import com.clothing.utils.AjaxMsg;
import com.clothing.utils.Utils;
import com.clothing.utils.page.Page;
import com.clothing.utils.page.Pageable;

/**
 * @ClassName: ArticleController 
 * @Description: TODO(文章) 
 * @author Charles.Tao 
 * @date 2017年9月7日 上午9:37:02 
 * @version 1.0
 */
@RequestMapping("/app/article")
@Controller("appArticleController")
public class ArticleController extends BaseController
{    
    @Autowired
    private ArticleTypeService articleTypeService;
    
    @Autowired
    private ArticleService articleService;
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private ArticlePraiseService articlePraiseService;
    
    /**
     * @Title: add 
     * @Description: TODO(发布文章) 
     * @param @param article
     * @param @param areaId
     * @param @param articleTypeId
     * @param @return 设定文件 
     * @return String 返回类型 
     * @throws
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ResponseBody
    public String add(Article article, Long areaId, Long articleTypeId)
    {
        if (!isValidNoMsg(article))
        {
            return getParameterErrorMsg();
        }
        
        List<ArticleImage> images = article.getImages();
        
        if (!Utils.isEmpty(images) && images.size() > 9)
        {
            return getParameterErrorMsg();
        }
        if (!Utils.isEmpty(images))
        {
            String prefix = CommonAttributes.SITE_URL;
            for (Iterator<ArticleImage> iterator = images.iterator(); iterator.hasNext();)
            {
                ArticleImage image = iterator.next();
                
                if (null == image)
                {
                    return getParameterErrorMsg();
                }
                
                if (!isValidNoMsg(image))
                {
                    return getParameterErrorMsg();
                }
                
                String imageUrl = image.getImage();
                
                if (imageUrl.startsWith(prefix))
                {
                    image.setImage(imageUrl.substring(prefix.length(), imageUrl.length()));
                }
            }
        }
        
        ArticleType articleType = articleTypeService.find(articleTypeId);
        
        if (null == articleType)
        {
            return AjaxMsg.failed("请选择文章类型");
        }
        
        User user = userService.getCurrent();
        article.setArticleType(articleType);
        article.setCreator(user);
        article.setStatus(Status.pass);
        articleService.save(article);
        
        return AjaxMsg.success("添加成功");
    }
    
    /**
     * @Title: update 
     * @Description: TODO(编辑文章) 
     * @param @param article
     * @param @param areaId
     * @param @param articleTypeId
     * @param @return 设定文件 
     * @return String 返回类型 
     * @throws
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ResponseBody
    public String update(Article formArticle, Long articleTypeId)
    {
        if (!isValidNoMsg(formArticle))
        {
            return getParameterErrorMsg();
        }

        List<ArticleImage> images = formArticle.getImages();

        if (!Utils.isEmpty(images) && images.size() > 6)
        {
            return getParameterErrorMsg();
        }

        if (!Utils.isEmpty(images))
        {
            String prefix = CommonAttributes.SITE_URL;
            for (Iterator<ArticleImage> iterator = images.iterator(); iterator.hasNext();)
            {
                ArticleImage image = iterator.next();

                if (null == image)
                {
                    return getParameterErrorMsg();
                }

                if (!isValidNoMsg(image))
                {
                    return getParameterErrorMsg();
                }

                String imageUrl = image.getImage();

                if (imageUrl.startsWith(prefix))
                {
                    image.setImage(imageUrl.substring(prefix.length(), imageUrl.length()));
                }
            }
        }

        Article article = articleService.find(formArticle.getId());

        if (null == article || article.getDeleted())
        {
            return getParameterErrorMsg();
        }

        User user = userService.getCurrent();

        if (!article.getCreator().getId().equals(user.getId()))
        {
            return getParameterErrorMsg();
        }

        ArticleType articleType = articleTypeService.find(articleTypeId);

        if (null == articleType)
        {
            return AjaxMsg.failed("请选择文章类型");
        }

        article.setArticleType(articleType);
        article.setContent(formArticle.getContent());
        article.setImages(images);
        article.setStatus(Status.unchecked);
        article.setAddress(formArticle.getAddress());
        article.setLongitude(formArticle.getLongitude());
        article.setLatitude(formArticle.getLatitude());
        articleService.update(article);
        
        return AjaxMsg.success("修改成功");
    }
    
    /**
     * @Title: list 
     * @Description: TODO(我发布的文章列表) 
     * @param @return 设定文件 
     * @return String 返回类型 
     * @throws
     */
    @RequestMapping(value = "/getList.json", method = RequestMethod.GET)
    @ResponseBody
    public String list(Status status, Pageable pageable)
    {
        User current = userService.getCurrent();
        Page<Article> page = articleService.findUserPage(current.getId(), status, pageable);
        JSONArray ja = null;
        
        if (page.getTotal() > 0)
        {
            ja = new JSONArray();
            
            for (Article article : page.getContent())
            {
                ArticleJson json = new ArticleJson();
                json.setId(article.getId());
                json.setContent(article.getContent());
                json.setCommentQuantity(article.getCommentQuantity());
                json.setImages(article.getFullImages());
                json.setPublishDate(article.getCreateDate());
                json.setStatus(article.getStatus());
                json.setArticleTypeName(article.getArticleType().getName());
                json.setBrowseQuantity(article.getBrowseQuantity());
                json.setPraiseQuantity(article.getPraiseQuantity());
                json.setAddress(article.getAddress());

                if (Status.notpass == status)
                {
                    json.setReason(article.getReason());
                }
                
                ja.add(json);
            }
        }
        
        return new AjaxMsg(true, page.getTotal(), ja).toString();
    }
    
    /**
     * @Title: detail 
     * @Description: TODO(详情) 
     * @param @param detail
     * @param @return 设定文件 
     * @return String 返回类型 
     * @throws
     */
    @RequestMapping(value = "/getDetail.json", method = RequestMethod.GET)
    @ResponseBody
    public String detail(Long id)
    {
        Article article = articleService.find(id);
        
        if (null == article || article.getDeleted())
        {
            return getParameterErrorMsg();
        }
        
        ArticleType type = article.getArticleType();
        User user = article.getCreator();
        ArticleJson json = new ArticleJson();
        json.setId(article.getId());
        json.setContent(article.getContent());
        json.setImages(article.getFullImages());
        json.setPublishDate(article.getCreateDate());
        json.setUserId(user.getId());
        json.setNickname(user.getNickname());
        json.setHeadImgUrl(user.getHeadImgUrl());
        json.setCommentQuantity(article.getCommentQuantity());
        json.setAddress(article.getAddress());
        json.setLongitude(article.getLongitude());
        json.setLatitude(article.getLatitude());
        json.setPraiseQuantity(article.getPraiseQuantity());
        json.setBrowseQuantity(article.getBrowseQuantity());
        json.setArticleTypeName(type.getName());
        json.setFullDate(article.getCreateDate());
        json.setArticleTypeId(type.getId());

        return new AjaxMsg(true, json).toString();
    }
    
    /**
     * @Title: listByType 
     * @Description: TODO(根据类型获取文章列表) 
     * @param @param articleTypeId
     * @param @param pageable
     * @param @return 设定文件 
     * @return String 返回类型 
     * @throws
     */
    @RequestMapping(value = "/getListByType.json", method = RequestMethod.GET)
    @ResponseBody
    public String listByType(Long articleTypeId, Pageable pageable)
    {
        Page<Article> page = articleService.findPageByTypeAndStatus(articleTypeId, Status.pass, Boolean.FALSE, pageable);
        JSONArray ja = null;
        
        if (page.getTotal() > 0)
        {
            ja = new JSONArray();
            Long userId = userService.getCurrentId(); 
            
            for (Article article : page.getContent())
            {
                ArticlePraise articlePraise = articlePraiseService.findOne(article.getId(), userId);
                ArticleType type = article.getArticleType();
                User user = article.getCreator();
                ArticleJson json = new ArticleJson();
                json.setId(article.getId());
                json.setContent(article.getContent());
                json.setImages(article.getFullImages());
                json.setPublishDate(article.getCreateDate());
                json.setUserId(user.getId());
                json.setNickname(user.getNickname());
                json.setHeadImgUrl(user.getHeadImgUrl());
                json.setCommentQuantity(article.getCommentQuantity());
                json.setAddress(article.getAddress());
                json.setLongitude(article.getLongitude());
                json.setLatitude(article.getLatitude());
                json.setPraiseQuantity(article.getPraiseQuantity());
                json.setBrowseQuantity(article.getBrowseQuantity());
                json.setArticleTypeName(type.getName());
                json.setPraise(articlePraise);
                json.setFullDate(article.getCreateDate());
                ja.add(json);
            }
        }
        
        return new AjaxMsg(true, page.getTotal(), ja).toString();
    }
    
    /**
     * @Title: browse 
     * @Description: TODO(浏览) 
     * @param @param articleId
     * @param @return 设定文件 
     * @return String 返回类型  
     * @throws
     */
    @RequestMapping(value = "/browse", method = RequestMethod.POST)
    @ResponseBody
    public String browse(Long articleId)
    {
        articleService.browseArticle(articleId);
        return AjaxMsg.success();
    }
    
    /**
     * @Title: praise 
     * @Description: TODO(赞) 
     * @param @return 设定文件 
     * @return String 返回类型  
     * @throws
     */
    @RequestMapping(value = "/praise", method = RequestMethod.POST)
    @ResponseBody
    public String praise(Long articleId)
    {
        Article article = articleService.find(articleId);
        
        if (null == article || article.getDeleted())
        {
            return getParameterErrorMsg();
        }
        
        User user = userService.getCurrent();
        articlePraiseService.praise(article, user);

        return AjaxMsg.success();
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ResponseBody
    public String delete(Long id) {
        Article article = articleService.find(id);
        if (null == article || article.getDeleted()) {
            return getParameterErrorMsg();
        }
        Long userId = userService.getCurrentId();
        if (!article.getCreator().getId().equals(userId)) {
            return getParameterErrorMsg();
        }
        article.setDeleted(Boolean.TRUE);
        articleService.update(article);

        return AjaxMsg.success();
    }
}
